# 
# install-tsp 
#

N='\E[m'
RED='\E[0;31m'
GREEN='\E[0;32m'
## ${GREEN}


# Deps
function install_deps {
   echo
   echo -e "${GREEN}Installing deps...$N"
   if [ -x /usr/bin/apt-get ];then
      echo -e "${GREEN}Installing needed dependencies...$N"
      echo
      sudo apt-get update > /dev/null
      sudo apt-get install curl php5-geoip unrar apache2 libapache2-mod-scgi php5 php5-cli \
      screen p7zip-rar libimdb-film-perl libxml-treepp-perl ssh rtorrent python-setuptools -y 
      echo
   else
      echo -e "${RED}apt-get not found, cant install deps$N"
      exit 1
   fi

}

function install_rt-tsp {

   cd
   echo
   echo "Install as current user `id -un` or as dedicated user rt?"
   echo
   echo -n "Install as rt y/n : "
   read answer

   case $answer in
          y)
      runasuser=rt
      if [ $install_type = ubuntu ];then
         sudo adduser --gecos "tsp system user" --disabled-login --disabled-password $runasuser
         RT_HOME=/home/$runasuser
      elif [ $install_type = optware ];then
         RT_HOME=/opt/home/$runasuser
         sudo adduser -g "tsp system user" -h $RT_HOME -s /opt/bin/bash $runasuser
      else
         # not shour if this works...
         sudo adduser $runasuser
         RT_HOME=/home/$runasuser
      fi

         ;;
          n)
      runasuser=`id -un`
      sudo groupadd rt
      sudo adduser $runasuser rt
      RT_HOME=/home/$runasuser

         ;;
   esac

   echo -e "${GREEN}Installing rt-tsp torrent standard platform...$N"

   if [ $install_type = optware ];then
      if [ ! -x $RT_HOME/bin/autosort.real ];then
         cd /opt/home
         wget "http://rt-tsp.googlecode.com/files/rt-tsp-1.0.tar.gz" -O /opt/home/rt-tsp.tar.gz
         tar zxvf rt-tsp.tar.gz -C $RT_HOME
         [ -f /opt/home/rt-tsp.tar.gz ] rm -f /opt/home/rt-tsp.tar.gz
         [ -L /opt/etc/init.d/S99rtorrentInit.sh ] || sudo ln -sf $RT_HOME/bin/rtorrentInit.sh /opt/etc/init.d/S99rtorrentInit.sh
      fi

   else
      if [ ! -x $RT_HOME/bin/autosort.real ] ;then
         wget "http://rt-tsp.googlecode.com/files/rt-tsp-1.0.tar.gz" -O /tmp/rt-tsp.tar.gz >> ~/tsp-install.log
         sudo -u $runasuser tar zxf /tmp/rt-tsp.tar.gz -C $RT_HOME
      fi
      [ $runasuser = rt ] || sudo -u $runasuser sed -i "s/user=\"rt\"/user=\"$runasuser\"/" $RT_HOME/bin/rtorrentInit.sh 
      [ -L /etc/init.d/rtorrentInit.sh ] || sudo ln -sf $RT_HOME/bin/rtorrentInit.sh /etc/init.d/rtorrentInit.sh && sudo mv /etc/init.d/rtorrentInit.sh /etc/init.d/rtorrentInit.sh.old ; sudo ln -sf $RT_HOME/bin/rtorrentInit.sh /etc/init.d/rtorrentInit.sh
      [ -L /etc/rc3.d/S20rtorrentInit.sh ] || sudo update-rc.d rtorrentInit.sh defaults

   fi

   [ -d $RT_HOME/.session ] || sudo -u $runasuser mkdir -v $RT_HOME/.session
   [ -d $RT_HOME/log ] || sudo -u $runasuser mkdir -v $RT_HOME/log

   [ -d $RT_HOME/torrents ] || sudo mkdir -v $RT_HOME/torrents
   for f in Anime appz gamez moviez Music seed TVSeries ;do
      if [ ! -d $RT_HOME/torrents/$f ];then
         sudo mkdir -v $RT_HOME/torrents/$f
      fi
   done
   sudo chown $runasuser:rt -R $RT_HOME/torrents
   sudo chmod 2777 -R $RT_HOME/torrents

   echo
   echo -e "${GREEN}Copying .rtorrent.rc please open ports 20000-20010 tcp/udp in your firewall.$N"
   if [ -f $RT_HOME/.rtorrent.rc ];then
      echo -e "${GREEN}If you want to use your existing config please check differences and update accordingly.$N"
      echo -e "${GREEN}It is best to say y here, a backup of your old one will be created as .rtorrent.rc~ ...$N"
      sudo -u $runasuser cp --backup=simple -i $RT_HOME/.rtorrent.rc.example $RT_HOME/.rtorrent.rc
   else
      sudo -u $runasuser cp $RT_HOME/.rtorrent.rc.example $RT_HOME/.rtorrent.rc
   fi

   sudo -u $runasuser cp --backup=simple $RT_HOME/.autosort.rc.example $RT_HOME/.autosort.rc

# Download env
   function DlBase {
      echo
      echo -e "${GREEN}Where do you want your downloads folder?$N"
      echo -e "${GREEN}This is the temporary data not where to actually store downloaded stuff (at least 50GB disk space)$N"
      echo -e "${GREEN}performance note, it is good to have this on a other disk than store$N"
      echo -e "${GREEN}If you enter /media/big here a /media/big/Downloads folder will be created...$N"
      echo -n "Base Download folder: "
      read DlBase junk

   }

   while [ -z "$DlBase" ] ;
   do
      DlBase
   done

   DlBase=$DlBase/Downloads
   echo
   echo -e "${GREEN}Creating Downloads folder structure...$N"
   for i in moviez gamez default appz Anime Music TVSeries seed ;do
      if [ ! -d $DlBase/$i ];then
         sudo mkdir -vp $DlBase/$i
      fi
   done
   echo
   echo -e "${GREEN}Setting perms rt:rt and 2775 for Downloads folder$N"
   sudo chown -R $runasuser:rt $DlBase
   sudo chmod -R 2775 $DlBase
   sudo ln -sf $DlBase $RT_HOME/Downloads

   function SfBase {
      echo
      echo -e "${GREEN}Where do you want your downloads to be Stored ?$N"
      echo -e "${GREEN}This is where to actually store downloaded stuff (disk space: lots...)$N"
      echo -e "${GREEN}This should be an empty or new folder$N"
      echo -e "${GREEN}If you want to store it in /media/big/{Apps,Movies,TVSeries} then enter /media/big here$N"
      echo -e "${GREEN}The folders {Apps, Movies/{New, DVDR, Bluray, DVDRip}, TVSeries, Games, Anime, Default}$N"
      echo -e "${GREEN}will be created automatic whit correct perms for users in group rt$N"
      echo -e "${GREEN}just export this folder whit samba or nfs for easy access$N"
      echo -e "${GREEN}a link to the torrents folder in $RT_HOME will be created here to...$N"
      echo -n "Base Store folder: "
      read SfBase junk

   }
   while [ -z "$SfBase" ] ;
   do
      SfBase
   done

   #SfBase=$SfBase/Downloads
   echo
   echo -e "${GREEN}Creating store folder structure and configuring autosort function...$N"
   for i in Movies Games Apps Anime Music TVSeries Default ;do
      if [ ! -d $SfBase/$i ];then
         if [[ $SfBase/$i =~ Movies ]];then
            sudo mkdir -vp $SfBase/$i/{New,DVDR,Bluray,DVDRip}
         else
            sudo mkdir -vp $SfBase/$i
         fi
         sudo chown -R $runasuser:rt $SfBase/$i
         sudo chmod -R 2775 $SfBase/$i
         sedrepl=$SfBase/$i
         sedrepl=${sedrepl//\//\\/}
         sudo -u $runasuser sed -i -e "s/${i}tag/$sedrepl/g" $RT_HOME/.autosort.rc
         sudo -u $runasuser sed -i -e "s/${i}tag/$sedrepl/g" $RT_HOME/.flexget/config.yml.example
      fi
   done

   sudo ln -sf $RT_HOME/torrents $SfBase/

   echo
   echo -e "${GREEN}Hove many days do you want to seed torrents ?$N"
   echo -e "${GREEN}Recommended is at least 7 days, min is 1 day$N"
   echo -n "seeddays: "
   read seeddays junk
   [ -z $seeddays ] && seeddays=5
   sudo -u $runasuser sed -i -e "s/seeddaystag/$seeddays/g" $RT_HOME/.autosort.rc

   # screen 
   echo
   echo -e "${GREEN}Configuring screen for multi user$N"
   sudo -u $runasuser cp $RT_HOME/.screenrc.example $RT_HOME/.screenrc
   [ -d /var/run/screen ] && sudo chmod 755 /var/run/screen
   [ -f /usr/bin/screen ] && sudo chmod u+s /usr/bin/screen
   echo
   echo -e "${GREEN}Adding user `id -un` as rt member and screen user...$N"
   echo "acladd `id -un`" |sudo -u $runasuser tee -a $RT_HOME/.screenrc >/dev/null
   #[ $install_type = optware ] || sudo adduser `id -un` rt

   echo -e "${GREEN}Setting rt's umask to 002 for compatibility, you should change this in /etc/.profile to.$N"
   echo "umask 002" |sudo -u $runasuser tee -a $RT_HOME/.profile >/dev/null

   if [ $install_type = optware ];then
      echo 
   else
      # Apache stuff
      echo
      echo -e "${GREEN}Enabling scgi...$N"
      sudo a2enmod scgi
      grep SCGIMount /etc/apache2/httpd.conf >/dev/null
      [ $? = 0 ] || echo "SCGIMount /RPC2 127.0.0.1:5000" | sudo tee -a /etc/apache2/httpd.conf >/dev/null
      sudo /etc/init.d/apache2 restart
   fi 
   sudo crontab -u $runasuser -l |grep -q TSP
   if [ $? = 0 ];then
      echo
      echo -e "${GREEN}TSP crontab already installed...$N"
   else
      echo
      echo -e "${GREEN}Installing crontab into $runasuser:s crontab...$N"
      if [ $runasuser = rt ] ;then
         cat > $RT_HOME/rt.crontab << EOF
##
# cron-jobs for TSP
##
MAILTO=root

# Clean Download Folders
00 00  * * *            ~/bin/cleanrt
00 05  * * *            ~/bin/cleandl

# Get Torrents
*/20 *  * * *           flexget --cron

# Get Subs
00 */12  * * *          ~/bin/getsub.pl -silent `grep MOVIE ~/.autosort.rc | awk -F"\"" {'print $2'}`

# Sort Movies
00 04  * * *            ~/bin/sort

# Setting perms for files and folders
00 01  * * *            sudo ~/bin/setperms 

# Rotating loggs...
48 16  * * *            sudo /usr/sbin/logrotate ~/.rt.logrot
EOF

         sudo crontab -u $runasuser $RT_HOME/rt.crontab
      else
         sudo crontab -u $runasuser -l > $RT_HOME/rt.crontab
	 cat >> $RT_HOME/rt.crontab << EOF

##
# cron-jobs for TSP
##

# Clean Download Folders
00 00  * * *            ~/bin/cleanrt
00 05  * * *            ~/bin/cleandl

# Get Torrents
*/20 *  * * *           flexget --cron

# Get Subs
00 */12  * * *          ~/bin/getsub.pl -silent `grep MOVIE ~/.autosort.rc | awk -F"\"" {'print $2'}`

# Sort Movies
00 04  * * *            ~/bin/sort

# Setting perms for files and folders
00 01  * * *            sudo ~/bin/setperms 

# Rotating loggs...
48 16  * * *            sudo /usr/sbin/logrotate ~/.rt.logrot
EOF

         sudo crontab -u $runasuser $RT_HOME/rt.crontab
      fi
      sudo rm $RT_HOME/rt.crontab
   fi

   sudo grep "$runasuser      ALL=NOPASSWD: /sbin/iptables, /usr/sbin/logrotate $RT_HOME/.rt.logrot, $RT_HOME/bin/setperms" /etc/sudoers >/dev/null
   if [ $? = 0 ];then
      echo
      echo -e "${GREEN}sudo for $runasuser already installed...$N"
   else
      echo
      echo -e "${GREEN}Installing needed sudo commands for $runasuser...$N"
      echo "$runasuser      ALL=NOPASSWD: /sbin/iptables, /usr/sbin/logrotate $RT_HOME/.rt.logrot, $RT_HOME/bin/setperms" |sudo tee -a /etc/sudoers >/dev/null
   fi
   # End install_rt-tsp
}

# Install xmlrpc-c...
function install_xmlrpc-c {
echo
echo -e "${GREEN}Installing xmlrpc-c-svn...$N"
svn co http://xmlrpc-c.svn.sourceforge.net/svnroot/xmlrpc-c/advanced /tmp/xmlrpc-c >> ~/tsp-install.log
cd /tmp/xmlrpc-c
echo -e "${GREEN}Configuring xmlrpc-c-svn...$N"
./configure --enable-tools >> ~/tsp-install.log
echo -e "${GREEN}Compiling xmlrpc-c-svn...$N"
make >> ~/tsp-install.log
[ $? == 0 ] && sudo make install >> ~/tsp-install.log
sudo ln -sf /usr/local/bin/xmlrpc /usr/bin/xmlrpc
cd
rm -rf /tmp/xmlrpc-c
}
# Install Rtorrent and libtorrent...

function install_libtorrent {
echo
echo -e "${GREEN}Installing libtorrent-0.12.6...$N"
cd /tmp
wget http://libtorrent.rakshasa.no/downloads/libtorrent-0.12.6.tar.gz
tar xzf libtorrent-0.12.6.tar.gz
rm -rf /tmp/libtorrent-0.12.6.tar.gz
cd /tmp/libtorrent-0.12.6
echo -e "${GREEN}Configuring libtorrent-0.12.6...$N"
./configure >> ~/tsp-install.log
echo -e "${GREEN}Compiling libtorrent-0.12.6...$N"
make >> ~/tsp-install.log
[ $? == 0 ] && sudo make install >> ~/tsp-install.log
cd
rm -rf /tmp/libtorrent-0.12.6
}

function install_rtorrent {
echo
echo -e "${GREEN}Installing rtorrent-0.8.6...$N"
cd /tmp
wget http://libtorrent.rakshasa.no/downloads/rtorrent-0.8.6.tar.gz
tar xzf rtorrent-0.8.6.tar.gz
rm -rf /tmp/rtorrent-0.8.6.tar.gz
cd /tmp/rtorrent-0.8.6/
wget http://rt-tsp.googlecode.com/files/rtorrent-0.8.6-canvas-fix.patch
echo -e "${GREEN}Applying canvas patch for colours in rtorrent...$N"
patch -p0 <./rtorrent-0.8.6-canvas-fix.patch
echo -e "${GREEN}Configuring rtorrent-0.8.6...$N"
./configure --with-xmlrpc-c=/usr/local/bin/xmlrpc-c-config  >> ~/tsp-install.log
echo -e "${GREEN}Compiling rtorrent-0.8.6...$N"
make >> ~/tsp-install.log
[ $? == 0 ] && sudo make install >> ~/tsp-install.log
cd
rm -rf /tmp/rtorrent-0.8.6
}

function install_rutorrent {
   # vars
   rut_ver="3.3"
   rut_plugs="cpuload diskspace _getdir rss seedingtime trafic data datadir erasedata scheduler throttle geoip extsearch"

   echo
   if [ ! -d /var/www ];then
      echo "no /var/www found where is your web servers document root?"
      echo -n "docroot: "
      read docroot junk
   else
      docroot=/var/www
   fi

   #if [ -d $docroot/rutorrent ];then
      

   echo -e "${GREEN}Installing rutorrent-$rut_ver web-gui to $docroot/rutorrent...$N"
   echo
   wget -q http://rutorrent.googlecode.com/files/rutorrent-$rut_ver.tar.gz -O /tmp/rutorrent.tar.gz
   sudo tar zxf /tmp/rutorrent.tar.gz -C $docroot/
   sudo chown -R www-data:rt $docroot/rutorrent
   sudo chmod 2775 $docroot/rutorrent


   echo -e "${GREEN}Installing rutorrent plugins to $docroot/rutorrent/plugins$N"
   echo
   for rut_plug in $rut_plugs ;do
      echo -e "Installing rutorrent plugin ${rut_plug}-${rut_ver}..."
      wget -q http://rutorrent.googlecode.com/files/$rut_plug-$rut_ver.tar.gz -O /tmp/$rut_plug.tar.gz
      sudo tar zxf /tmp/$rut_plug.tar.gz -C $docroot/rutorrent/plugins/
   done 
   sudo chown -R www-data:rt $docroot/rutorrent
   sudo chmod -R g+w $docroot/rutorrent
   sudo sed -i -e s/"$forbidUserSettings = false;"/"$forbidUserSettings = true;"/g $docroot/rutorrent/conf/config.php

   echo -e "${GREEN}Configuring webserver$N"
   if [ ! -f $docroot/rutorrent/.htaccess ] ;then 
   cat << EOF | sudo tee $docroot/rutorrent/.htaccess >/dev/null
   AuthType Digest
   AuthName "rutorrent"
   AuthUserFile $docroot/rutorrent/.htpasswd
   require valid-user
EOF
   fi
      sudo a2enmod auth_digest
      sudo /etc/init.d/apache2 restart
      echo
      echo -e "${GREEN}Adding `id -un` as rutorrent user$N"
      sudo htdigest -c $docroot/rutorrent/.htpasswd rutorrent `id -un`
      echo
      echo -e "${RED}To enable auth logins please change AllowOverride none to: AllowOverride AuthConfig in your web servers default config$N"
      echo -n "Hit Enter"
      read junk
}

function install_flexget {

   flexget_test=`which flexget`

   if [[ ! -z $flexget_test ]] ;then
      echo
      echo -e "${GREEN}Flexget alredy installed...$N"
   else
      echo
      echo -e "${GREEN}Installing Flexget...$N"
      echo
      sleep 1
      sudo easy_install -q flexget
      flexget_ret=$?
   if [ $flexget_ret = 0 ];then
      echo -e "${GREEN}Installed OK...$N"
   else
      echo -e "${RED}Something went wrong check tsp-install.log$N"
      exit 1
   fi
   fi

   echo -e "${GREEN}Please copy /home/rt/.flexget/config.yml.example to config.yml and edit for your needs$N"
   echo -e "${GREEN}Then run flexget -v --initdb as user rt to initialise the db$N"
   echo -n "Hit Enter"
   read junk

}

#do pre checks...

arch_check=`uname -m`

if [[ $arch_check =~ x86_64|i686 ]] ;then
   platform=x86
   if which dpkg &> /dev/null ;then
      install_type=ubuntu
   else
      install_type=unknown
   fi
else
   platform=nas
   if [ ! `id -u` = 0 ];then
      echo "you need to be root for nas install"
      exit 1
   fi
   if ipkg list |grep rtorrent &> /dev/null ;then
         install_type=optware
   else
         echo "optware is needed for nas installs."
         echo "Please make shoure optware can be installed..."
         exit 1
   fi
fi

echo
echo -e "${GREEN}        #######  #####  ######
           #    #     # #     #
           #    #       #     #
           #     #####  ######
           #          # #
           #    #     # #
           #     #####  # ${RED}installer version 0.0.1$N"
echo 
echo $install_type
echo $platform
echo 
echo -e "${GREEN}You are about to install TSP Torrent Standard Platform...$N"
echo -e "${GREEN}This is created for ubuntu linux but should work for any linux
if you install rtorrent 0.8.6+ and xmlrpc-c 0.11.0+ by your self then you can run $0 nodeps
If you want the script to compile rtorrent and xmlrpc-c for you but are not running debian based system
you can run $0 noapt after installing all the necessary building dependences...$N"
echo -n "Hit Enter"
read junk
 

case $install_type in
      optware)
         install_rt-tsp
         install_rutorrent
         install_flexget
         ;;
      unknown)
         install_xmlrpc-c
         install_libtorrent
         install_rtorrent
         install_rt-tsp
         install_rutorrent
         install_flexget
         ;;
      ubuntu)
         install_deps
#         install_xmlrpc-c
#         install_libtorrent
#         install_rtorrent
         install_rt-tsp
         install_rutorrent
         install_flexget
         ;;
esac

echo
echo "you are done."
cd

# vim:ts=3:sw=3
